package com.woniuxy.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.woniuxy.entity.User;
import com.woniuxy.util.HibernateUtil;
import com.woniuxy.util.PageUtil;

public class UserDAO {
//	private JDBC jdbc = JDBC.getIntance();
	
	private Session session;
	
	public UserDAO(){
		if(session != null)
			session.close();
		session = HibernateUtil.getSessionFactory().openSession();
	}
	
	public boolean getById(int id){
		
		return false;
	}
	
	public User getUserByName(String userName){
		
		User user = null;
		try {
			Query query = session.createQuery("FROM User WHERE userName = ?");
			query.setString(0,userName);
			ArrayList<User> list= (ArrayList<User>) query.list();
			user = list.get(0);
			return user;
		} catch (Exception e) {			
			
		}
		return null;
	}
	
	public List<User> getAllUser(){
		List<User> list = new ArrayList<User>();
		try {
			list = session.createQuery("FROM User").list();			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}
	
	public boolean insertUser(User user){
		Transaction transaction = session.beginTransaction();
		try {
			session.save(user);
			transaction.commit();
			PageUtil.setUsers(getAllUser());
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}
	
	public boolean delete(User user){
		Transaction transaction = session.beginTransaction();
		try {
			session.delete(user);
			transaction.commit();
			PageUtil.setUsers(getAllUser());
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}
	
}
